package org.cn.lennon.mybatis.transcation.impl;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.cn.lennon.mybatis.transcation.Transaction;

/**
 * 通过jdbc的事务来了解mybatis是如何处理事务
 * 
 * @author lennon
 *
 */
public class JdbcTransaction implements Transaction {

	private boolean autoCommmit;
	private Connection connection;

	public JdbcTransaction(Connection connection) {
		this.connection = connection;
	}
	
	public JdbcTransaction(Connection connection, boolean autoCommmit) {
		this.connection = connection;
		this.autoCommmit = autoCommmit;
	}

	public Connection getConnection() throws SQLException {
		if(connection == null) {
			openConnection();
		}
		return connection;
	}
	
	public void openConnection() throws SQLException {
	    connection.setAutoCommit(autoCommmit);
	}

	/**
	 * 从jdbc的代码中是如何开启事务的，然后简单封装一下，再简单过以下mybais又是如何做的
	 */
	public void commit() throws SQLException {
		if(!autoCommmit) {
			this.connection.commit();
		}
	}

	public void rollback() throws SQLException {
		if(!autoCommmit) {
			this.connection.rollback();
		}
	}

	public void close() throws SQLException {
		if(this.connection != null) {
			this.connection.close();
		}
	}

	public boolean isAutoCommmit() {
		return autoCommmit;
	}

	public void setAutoCommmit(boolean autoCommmit) {
		this.autoCommmit = autoCommmit;
	}
}
